import { defineStore } from 'pinia'
import { reqLogin, reqLoginOut, reqUserInfo } from '@/api/user'
import type {LoginResponse,UserInfoResponse,LoginRequest} from '@/api/user/type'
import { useRouter } from 'vue-router'
import { ElNotification } from 'element-plus'
import Cookies from 'js-cookie'
import { Avatar } from '@element-plus/icons-vue'
import { GET_TOKEN, DEL_TOKEN, SET_TOKEN } from '@/utils/token'

let useUserStore = defineStore('User', {
  state() {
    return {
      token: GET_TOKEN(),
      userName: '',
      avatar: '',
    }
  },
  actions: {
    async login(data: LoginRequest) {
      let res;
      try{
        res= await reqLogin(data)
      }catch(e:any){
        return Promise.reject(new Error(e.message))
      }
       console.log(res);
      if (res.status == 200) {
        this.token = res.token
        SET_TOKEN(res.token)
        // Cookies.set('cookie', res.token)
        return res.token
      } else {
        //  throw new Error(res.data.message);
        // ElNotification({ title: '消息', message: '账号或密码错误！', type: 'error' })
        // console.log(res)
        return Promise.reject(new Error("未知原因登录失败！"))
        // console.log(res.message)
        // throw new Error(res.data);
      }
    },
    async Init() {
      let res
      try{
      res = await reqUserInfo()
      console.log('路由守卫');
      console.log(res);
      }catch(e){
      console.log('路由守卫错误');
      console.log(e);


      }
      return
      if (res.code == '200') {
        this.userName = res.data.name
        this.avatar = res.data.avatar
        return 'ok'
      } else {
        return Promise.reject(new Error(res.message))
      }
    },
    async logout() {
      let result = await reqLoginOut()
      if (result.code == 200) {
        this.userName = ''
        this.avatar = ''
        this.token = ''
        DEL_TOKEN()
        return 'ok'
      }
      else{
        return Promise.reject(new Error(result.message))
      }
    },
  },
  getters: {},
})

export default useUserStore
